package org.wdm.servlets;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.wdm.analysis.Evaluator;
import org.wdm.analysis.SimpleEvaluator;
import org.wdm.beans.Crime;
import org.wdm.beans.Result;
import org.wdm.beans.Route;
import org.wdm.beans.Step;
import org.wdm.beans.points.BusStopPoint;
import org.wdm.beans.points.Point;
import org.wdm.hibernateUtils.HibernateUtil;
import org.wdm.parsers.GeocodingParser;
import org.wdm.parsers.GoogleParser;
import org.wdm.parsers.TransportParser;
import org.wdm.utils.BusStopPointDeserializer;
import org.wdm.utils.BusStopPointSerializer;
import org.wdm.utils.PointDeserializer;
import org.wdm.utils.PointSerializer;

/**
 *
 * @author iakopap
 */
public class RouterServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("Process started");
        //Reading the request parameters
        String from = request.getParameter("from");
        String to = request.getParameter("to");
        String alters = request.getParameter("alternatives");
        String mode = request.getParameter("mode");
        
        Point start = GeocodingParser.parse(from);
        Point end = GeocodingParser.parse(to);

        //Getting all the alternative google routes
        List<Route> groutes = new ArrayList<Route>();

        if(mode.equals("walking")){
            groutes.addAll(GoogleParser.parse(start.toString(), end.toString(), alters, "walking"));
        } else if(mode.equals("driving")){
            groutes.addAll(GoogleParser.parse(start.toString(), end.toString(), alters, "driving"));
        } else {
            groutes.addAll(TransportParser.parse(start, end));
        }
        
        

        

        getCrimesPolice(groutes, request);

        Evaluator e = new SimpleEvaluator();
        double[] scores = new double[groutes.size()];
        int i = 0;
        //Printing all the available routes
        for (Route route : groutes) {
            scores[i] = e.evaluate(route);
            System.out.println("Route: " + route.getSummary() + " score= " + scores[i]);
            System.out.println(route);
            i++;
        }

        TreeSet<Route> routesSet = new TreeSet<Route>(groutes);
//        Result result = new Result(groutes);

        response.setContentType("application/json");
        // Get the printwriter object from response to write the required json object to the output stream      
        PrintWriter out = response.getWriter();
        // Assuming your json object is **jsonObject**, perform the following, it will return your json object 
        
        
        

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(BusStopPoint.class, new BusStopPointSerializer());
        gsonBuilder.registerTypeAdapter(Point.class, new PointSerializer());
        Gson gson = gsonBuilder.create();
        
//        String jsonString = gson.toJson(routesSet.first());
//        
//        gsonBuilder = new GsonBuilder();
//        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
//        gsonBuilder.registerTypeAdapter(Point.class, new PointDeserializer());
//        gsonBuilder.registerTypeAdapter(BusStopPoint.class, new BusStopPointDeserializer());
//        gson = gsonBuilder.create();
//        Route myroute = gson.fromJson(jsonString, Route.class);
//        
//        if(myroute.getSteps().get(0).getTravelMode() == null){
//            out.print("why");
//        }
//        
//        if(myroute.getSteps().get(2).getStart() instanceof BusStopPoint){
//            out.print("yeah");
//        } else {
//            out.print("no");
//        }
        
        out.print(gson.toJson(routesSet.first()));
        
//        StringWriter jsonStringWriter = new StringWriter();
//        ObjectMapper mapper = new ObjectMapper();
//        try {
//            mapper.writeValue(jsonStringWriter, routesSet.pollFirst());
//        } catch (JsonGenerationException ex) {
//            Logger.getLogger(RouterServlet.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (JsonMappingException ex) {
//            Logger.getLogger(RouterServlet.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        String json = jsonStringWriter.toString();
//        out.print(json);
//        
//        mapper = new ObjectMapper(); 
//        Route route = mapper.readValue(json, Route.class);
//        
//        if(route.getSteps().get(2).getStart() instanceof BusStopPoint){
//            out.print("yeah");
//        } else {
//            out.print("no");
//        }
        
        
        out.flush();
//        System.out.println("Process started");
//        //Reading the request parameters
//        String from = request.getParameter("from");
//        String to = request.getParameter("to");
//        String alters = request.getParameter("alternatives");
//
//        Point start = GeocodingParser.parse(from);
//        Point end = GeocodingParser.parse(to);
//
//        //Getting all the alternative google routes
//        List<Route> groutes = new ArrayList<Route>();
//
//        groutes.addAll(GoogleParser.parse(start.toString(), end.toString(), alters, "walking"));
//        groutes.addAll(GoogleParser.parse(start.toString(), end.toString(), alters, "driving"));
//
//        groutes.addAll(TransportParser.parse(start, end));
//
//        getCrimesPolice(groutes, request);
//
//        Evaluator e = new SimpleEvaluator();
//        double[] scores = new double[groutes.size()];
//        int i = 0;
//        //Printing all the available routes
//        for (Route route : groutes) {
//            scores[i] = e.evaluate(route);
//            System.out.println("Route: " + route.getSummary() + " score= " + scores[i]);
//            System.out.println(route);
//            i++;
//        }
//
//        Result result = new Result(groutes);
//
//        response.setContentType("application/json");
//        // Get the printwriter object from response to write the required json object to the output stream      
//        PrintWriter out = response.getWriter();
//        // Assuming your json object is **jsonObject**, perform the following, it will return your json object  
//        Gson gson = new Gson();
//        out.print(gson.toJson(result));
//        out.flush();

//        request.setAttribute("routes", groutes);
//
//        //Dispatchig the request
//        RequestDispatcher rd = getServletContext().getRequestDispatcher("/WEB-INF/jsp/resultsDisplay.jsp");
//        rd.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void getCrimesPolice(List<Route> list, HttpServletRequest request) {
        for (Route route : list) {
            for (Step step : route.getSteps()) {
                List<Crime> crimeList = new ArrayList<Crime>();
                    SessionFactory factory = HibernateUtil.getSessionFactory();
                    Session session = factory.openSession();
                    Query q = session.createQuery(
                            "select e from Crime as e where e.cords.latitude<=:lat and e.cords.latitude>=:lat2 and e.cords.longitude<=:lon and e.cords.longitude>=:lon2 "
                            + "and (e.category=:cat1 "
                            + "or e.category=:cat2 "
                            + "or e.category=:cat3 "
                            + "or e.category=:cat4 "
                            + "or e.category=:cat5 "
                            + "or e.category=:cat6 "
                            + "or e.category=:cat7 "
                            + "or e.category=:cat8 "
                            + "or e.category=:cat9 "
                            + "or e.category=:cat10 "
                            + "or e.category=:cat11)");
                    q.setParameter("lat", step.getBoundingBox().getMaxLatitude());
                    q.setParameter("lat2", step.getBoundingBox().getMinLatitude());
                    q.setParameter("lon", step.getBoundingBox().getMaxLongitude());
                    q.setParameter("lon2", step.getBoundingBox().getMinLongitude());
                    q.setParameter("cat1", "anti-social-behaviour");
                    q.setParameter("cat2", "public-disorder-weapons");
                    q.setParameter("cat3", "shoplifting");
                    q.setParameter("cat4", "other-theft");
                    q.setParameter("cat5", "drugs");
                    q.setParameter("cat6", "burglary");
                    q.setParameter("cat7", "robbery");
                    q.setParameter("cat8", "violent-crime");
                    q.setParameter("cat9", "criminal-damage-arson");
                    q.setParameter("cat10", "other-crime");
                    q.setParameter("cat11", "vehicle-crime");

                    List<Crime> crimes = q.list();
                    crimeList.addAll(crimes);
                    session.close();
                    System.out.println("!!!!!!!!!!!!!NUMBER OF CRIMES:" + crimeList.size());
                    step.addCrimes(crimeList);
            }
        }
    }
}
